<template>
    <div class='delivery'>
        <div class="container">
            <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" class="search-con">
                <el-form-item label="收货人地址" prop="key">
                    <el-input v-model="queryParams.key" placeholder="请输入" clearable size="small" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form>
            <el-row :gutter="10" class="mb8">
                <el-col :span="22">
                    <el-button type="primary" icon="el-icon-plus" size="mini" @click="title='新增';handleShow='add'" v-hasPermi="['user:depart:add']">
                        新增</el-button>
                        <el-button type="primary" size="mini" @click="handleDeletes()"
                        v-hasPermi="['product:manage:add']">批量删除</el-button>
                </el-col>
                <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
            <el-table border v-loading="loading" :data="tableList" ref="tableList" v-tableHeight :height="tableList.length>0?'900px':'120px'">
                <el-table-column type="selection" width="55" />
                <el-table-column label="编号" align="center" prop="id" width="120" />
                <el-table-column label="收货人姓名" align="center" prop="name" width="180"/>
                <el-table-column label="收货人联系方式" align="center" prop="mobile" width="180"/>
                <el-table-column label="收货人地址" align="center" show-overflow-tooltip >
                    <template slot-scope="scope">
                        <span>{{scope.row.province}}{{ scope.row.city }}{{ scope.row.area }}{{ scope.row.detailed }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="默认地址" align="center" prop="is_default" width="120">
                    <template slot-scope="scope">
                        <span>
                            {{selectDictLabel(yesNo, scope.row.is_default)}}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                        <el-button size="mini" type="text" icon="el-icon-edit" @click="title='编辑';form=JSON.parse(JSON.stringify(scope.row));handleShow='edit'"
                            v-hasPermi="['user:depart:edit']">
                            编辑
                        </el-button>
                        <el-button  v-if="scope.row.is_default==0" size="mini" type="text" @click="handleAble(scope.row)" v-hasPermi="['user:depart:stop']">设为默认地址
                        </el-button>
                        <el-button v-if="scope.row.is_default==1" size="mini" type="text" @click="handleAble(scope.row)" v-hasPermi="['user:depart:start']">取消默认地址
                        </el-button>
                        <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['user:depart:del']">
                            删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="pageCount>0" :pageCount="pageCount" :page.sync="queryParams.page" :limit.sync="queryParams.limit" @pagination="getList" />
        </div>
        <el-dialog :title="title" visible v-if="handleShow" @close="close()" width="60%" append-to-body :close-on-click-modal="false">
            <el-form ref="form" :model="form" :rules="rules" label-width="120px" v-loading="formLoading">
                    <el-row>
                        <el-col :span="10">
                            <el-form-item label="收货人姓名：" prop="name">
                                <el-input v-model="form.name" placeholder="请输入收货人名称" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" :offset="2">
                            <el-form-item label="联系方式：" prop="mobile">
                                <el-input v-model="form.mobile" placeholder="请输入联系方式" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-col :span="12">
                                <el-form-item label="所属省份:" prop="province">
                                    <el-select v-model="form.province" placeholder="请选择所属省份"
                                        @change="getCurrentCity" clearable>
                                        <el-option v-for="dict in areaData" :key="dict.code" :label="dict.name"
                                            :value="dict.name" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="所属城市:" prop="city">
                                    <el-select v-model="form.city" placeholder="请选择所属城市"
                                        @change="getCurrentArea" filterable clearable>
                                        <el-option v-for="dict in currentCityList" :key="dict.code" :label="dict.name"
                                            :value="dict.name" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="所属区/县：" prop="area">
                                    <el-select  v-model="form.area" placeholder="请选择所属区/县" filterable
                                        clearable>
                                        <el-option v-for="dict in currentAreaList" :key="dict.code" :label="dict.name"
                                            :value="dict.name" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="详细地址：" prop="detailed">
                                    <el-input v-model="form.detailed" placeholder="请输入详细地址" />
                                </el-form-item>
                            </el-col>
                        </el-col>
                          <el-col :span="12">
                            <el-form-item label="是否默认" prop="is_default" >
                                <el-radio-group v-model="form.is_default">
                                    <el-radio v-for="dict in yesNo" :key="dict.dictValue" :label="Number(dict.dictValue)">{{ dict.dictLabel }}
                                    </el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="close()">取 消</el-button>
                <el-button type="primary" @click="submit" :disabled="formLoading">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import { getAddressLists, setAddressInfo, delAddres, setAddresDefault } from "@/api/purchaseOrder/purchase.js"
import { isvalidatemobile, isvalidateTel } from "@/utils/validate";
import { yesNo } from "@/api/dictionary"

import throttle from 'lodash.throttle'
export default {
    name: 'delivery',
    props: {

    },
    data() {
        const ismobile = (rule, value, callback) => {
            if (isvalidatemobile(value)[0]) {
                callback(new Error(isvalidatemobile(value)[1]))
            } else {
                callback()
            }
        }
        return {
            showSearch: true,
            loading: false,
            pageCount: 0,
            total: 0,
            queryParams: {
                page: 1,
                limit: 20,
                key: null,
            },
            tableList: [{
                id:1
            }],
            // statusList: departStatus,
            handleShow: "",
            formLoading: false,
            currentCityList: [],
            currentAreaList: [],
            form: {
                id: null,
                name: null,
            },
            rules: {
                name: [{ required: true, message: '请输入收货人姓名', trigger: 'blur' }],
                mobile: [{ required: true, message: "请输入联系方式", trigger: "blur" }, { validator: ismobile, trigger: 'blur' }],
                province: [{ required: true, message: '请选所属省份', trigger: 'change' }],
                city: [{ required: true, message: '请选择所属城市', trigger: 'blur' }],
                area: [{ required: true, message: '请选择所属区/县', trigger: 'blur' }],
                detailed: [{ required: true, message: '请输入所属详细地址', trigger: 'blur' }],
                is_default: [{ required: true, message: '请选择是否默认', trigger: 'change' }],
            },
            title: "",
            yesNo: yesNo,
            codeList: [],
            // addres_id:'',
        }
    },
    created() {
        this.getList()
        // if (this.form.province) {
        //         this.currentCityList = this.areaData.find(item => item.name == this.form.province).cityList
        //     }
        //     // this.$set(this.form, "city", this.data.city)
        //     if (this.form.city) {
        //         this.currentAreaList = this.currentCityList.find(item => item.name == this.form.city).areaList
        //     }
    },
    methods: {
        getList() {
            this.loading = true;
            getAddressLists(this.queryParams).then(res => {
                this.tableList = res.data.lists;
                this.pageCount = res.data.pageCount;
                this.loading = false;
            });
        },
        getCurrentCity(val) {
            if (val) {
                this.$set(this.form, "city", null)
                this.$set(this.form, "area", null)
                this.currentAreaList = []
                this.currentCityList = this.areaData.find(item => item.name == val).cityList;
            }
        },
        getCurrentArea(val) {
            if (val) {
                this.$set(this.form, "area", null)
                this.currentAreaList = this.currentCityList.find(item => item.name == val).areaList;
            }
        },

        handleQuery() {
            this.queryParams.page = 1;
            this.getList();
        },
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        close() {
            this.form = {}
            this.handleShow = ""
        },
        handleAble(row) {
            let label = row.is_default == 0 ? '设为默认' : '取消默认';
            this.$confirm(`是否将“${row.name}”${label}?`, "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function () {
                return setAddresDefault({ address_id: row.id });
            }).then(() => {
                this.getList();
                this.msgSuccess(`${label}成功`);
            })
        },
        handleDelete(row) {
            this.$confirm('是否确认删除' + '"' + row.name + '"' + '?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function () {
                return delAddres({ addres_ids: row.id });
            }).then(() => {
                this.getList();
                this.msgSuccess("删除成功");
            })
        },

        toggleSelection(row) {
            this.$refs.tableList.toggleRowSelection(row);
        },
        handleDeletes(selection) {
            this.codeList = []
            this.selectData = this.$refs.tableList.selection;
            console.log(this.selectData, 'xuanzhongdata')
            if (this.selectData.length == 0) {
                this.$confirm('请选择上架中的商品进行批量操作', "警告", {
                    confirmButtonText: "确定",
                    type: "warning"
                })
            } else if (this.selectData.length > 0) {
                for (let i = 0; i < this.selectData.length; i++) {
                    let codes = this.selectData[i].id
                    this.codeList.push(codes)
                    console.log(this.codeList, 'ids')
                }
                let a = this.codeList.join(",")
                console.log(a, 'ids')
                this.$confirm('是否确认批量删除这些地址' + '?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function () {
                return delAddres({ addres_ids: a });
            }).then(() => {
                this.getList();
                this.msgSuccess("删除成功");
            })
               
            }
        },

        submit: throttle(function () {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    this.formLoading = true;
                    this.form.addres_id = this.form.id ? this.form.id : null
                    setAddressInfo(this.form).then(res => {
                        this.msgSuccess("操作成功！");
                        this.close()
                        this.formLoading = false;
                        this.getList();
                    }).catch(() => {
                        this.formLoading = false;
                    })
                }
            })
        }, 1000, { trailing: false }),
    }
}
</script>

<style lang='scss' scoped>
</style>
